package com.ziytek.web.citizen.util;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;

/**
 * @author fenghx
 * @version 1.0
 * @className AccessToken
 * Description:
 * @date 2024/3/12 11:02
 */
@Getter
@Slf4j
public class AccessToken {
    private String userId;
    private String phoneNum;
    private long createTime;
    private String token;

    private AccessToken() {
    }

    public static AccessToken encryptAndGetAccessToken(SecureKey authorizeKey, String userId, String phoneNum) {
        AccessToken accessToken = new AccessToken();
        accessToken.userId = userId;
        accessToken.phoneNum = phoneNum;
        accessToken.createTime = System.currentTimeMillis();
        accessToken.token = encryptAccessToken(authorizeKey, userId, phoneNum);
        return accessToken;
    }

    public static String encryptAccessToken(SecureKey authorizeKey, String userId, String phoneNum) {
        return authorizeKey.encrypt(String.format("%s,%s,%s", userId, phoneNum, System.currentTimeMillis()));
    }

    public static AccessToken decryptAccessToken(SecureKey authorizeKey, String secretToken) {
        if (StringUtil.isEmpty(secretToken)) {
            return null;
        }

        AccessToken accessToken;
        try {
            String token = authorizeKey.decrypt(secretToken);
            accessToken = new AccessToken();
            String[] tokens = token.split(",");
            if (3 != tokens.length) {
                log.error(String.format("token有问题：secretToken[%s]", secretToken));
                return null;
            }

            accessToken.userId = tokens[0];
            accessToken.phoneNum = tokens[1];
            accessToken.createTime = NumberUtils.toLong(tokens[2], System.currentTimeMillis());
            accessToken.token = secretToken;
        } catch (Exception var5) {
            //var5.printStackTrace();
            log.error(String.format("token解密失败：authorizeKey[%s] secretToken[%s]", authorizeKey, secretToken), var5);
            accessToken = null;
        }

        return accessToken;
    }
}